package com.hfzy.ihk.web.linkcall.controller.callTask;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.facade.enums.CustomerFollowCategory;
import com.hfzy.ihk.common.facade.enums.CustomerNeedLevel;
import com.hfzy.ihk.common.facade.enums.call.CommitTo;
import com.hfzy.ihk.common.support.redis.IdGenerator;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.file.excel.ExcelUtils;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.util.uuid.base64uuid.UUIDs;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.calldata.entity.CallHistory;
import com.hfzy.ihk.facade.calldata.entity.CallTaskDetail;
import com.hfzy.ihk.facade.calldata.enums.PageFrom;
import com.hfzy.ihk.facade.calldata.enums.WhereFrom;
import com.hfzy.ihk.facade.calldata.service.EsOptRmiService;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlowStep;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.task.CallTask;
import com.hfzy.ihk.facade.linkcall.entity.task.CallTaskPhone;
import com.hfzy.ihk.facade.linkcall.enums.*;
import com.hfzy.ihk.facade.linkcall.vo.ResultVo;
import com.hfzy.ihk.facade.linkcall.vo.UserVo;
import com.hfzy.ihk.facade.linkcall.vo.flow.config.SearchPackageVo;
import com.hfzy.ihk.facade.linkcall.vo.task.*;
import com.hfzy.ihk.facade.linkcall.vo.task.EchartVo.PieVo;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.facade.userCenter.enums.CallLineType;
import com.hfzy.ihk.facade.userCenter.enums.CallType;
import com.hfzy.ihk.web.linkcall.biz.CallDataBiz;
import com.hfzy.ihk.web.linkcall.support.annotation.PreProcessParam;
import com.hfzy.ihk.web.linkcall.support.annotation.ReceiveUserPrivParam;
import com.hfzy.ihk.web.linkcall.biz.CallTaskBiz;
import com.hfzy.ihk.web.linkcall.biz.CallTaskPhoneBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowStepBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.dao.CallTaskRepository;
import com.hfzy.ihk.web.linkcall.utils.CallTaskUtils;
import com.hfzy.ihk.web.linkcall.utils.LayUiParamUtils;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import com.hfzy.ihk.web.oauth.client.conf.OAuthClientSecurityConfig;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import org.apache.catalina.User;
import org.apache.http.HttpRequest;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;


/**
 * 智能外呼管理
 */
@Controller
@RequestMapping("/linkageCall")
public class LinkageCallController {

    @Reference(version = "1.0.0")
    EsOptRmiService esOptRmiService;

    @Autowired
    CallTaskRepository callTaskRepository;

    @Autowired
    CallTaskBiz callTaskBiz;

    @Autowired
    CallDataBiz callDataBiz;

    @Autowired
    CallTaskPhoneBiz callTaskPhoneBiz;

    @Autowired
    SpeakingPackageBiz speakingPackageBiz;

    @Autowired
    SpeakingFlowStepBiz speakingFlowStepBiz;

    @Autowired
    SpeakingFlowBiz speakingFlowBiz;

    @Value("${cloudcall.call-url}")
    private  String callUrl;

    @Value("${cloudcall.ws-url}")
    private  String wsUrl;

    @Value("${freeswitch.serviceUrl}")
    private String freeswitchCallService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    RestTemplate restTemplate;


    @Value("${freeswitch.checkUAUrl}")
    String checkUAUrl;


    Logger logger = LoggerFactory.getLogger(LinkageCallController.class);

//    ThreadPoolTaskExecutor threadPoolTaskExecutor;

//    @ReceiveUserPrivParam
    @RequestMapping("/queryLinkageCallTask")
    public String index(Model model,HttpServletRequest request) {
        UserInfo userInfo = UserUtil.getLoginUser();
        model.addAttribute("taskStatus", CallTaskStatus.values());
        model.addAttribute("connectWsVo", CallTaskUtils.getConnectWsVo("33", PageFrom.PC_AI_CALL.getValue(),"3"));
        model.addAttribute("fsConnectWsVo", CallTaskUtils.getFreesWitchConnectWsVo());
        model.addAttribute("pageFrom",PageFrom.PC_AI_CALL.getValue());
        return "page/linkageCall/queryLinkageCallTask";
    }

    @RequestMapping("/addLinkageCallTask")
    public String addLinkageCallTask(Model model) {
        Map<String,String> param = new HashMap<>();
        param.put("checkStatus", CheckStatus.YES.getValue());
        List<SpeakingPackage> speakingPackages = speakingPackageBiz.getSpeakingPackageList(param);
        model.addAttribute("speakingPackages",speakingPackages);
        return "page/linkageCall/addLinkageCallTask";
    }

    @ResponseBody
    @RequestMapping("/queryCallTaskPhoneMsg")
    public WebResult queryCallTaskPhoneMsg(@RequestParam(value = "taskId") String taskId) {
        WebResult webResult = new WebResult();
        if (Utils.isNullString(taskId) || "0".equals(taskId)) {
            List<Map> mapList = new ArrayList<Map>();
            CallTaskPhoneSource[] callTaskPhoneSourceList = CallTaskPhoneSource.values();
            for (CallTaskPhoneSource callTaskPhoneSource : callTaskPhoneSourceList) {
                if(callTaskPhoneSource != CallTaskPhoneSource.EBOOK_CUSTOMER_INFO){
                    Map map = new HashMap() {
                    };
                    map.put("sourceName", callTaskPhoneSource.getDesc());
                    map.put("num", "-");
                    mapList.add(map);
                }
            }
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);
            webResult.setRecords(mapList);
            webResult.setTotal(mapList.size());
        } else {
            //根据task id 返回查询的calltaskPhone 的详情
        }
        return webResult;
    }

    @RequestMapping("/queryLinkageCallTaskDetail")
    public String queryLinkageCallTaskDetail(Model model) {
        return "page/linkageCall/queryLinkageCallTaskDetail";
    }

    /**
     *
     * @param model
     * @param mainCallPhone
     * @param targetCallPhone
     * @param taskId
     * @param aiCall
     * @param freeswitchCall 是否使用freeswitch进行外呼操作,默认为否
     * @return
     */
    @RequestMapping("/callDetail")
    public String callDetail(Model model,@RequestParam String mainCallPhone,@RequestParam String targetCallPhone,@RequestParam String taskId,@RequestParam boolean aiCall,@RequestParam(defaultValue = "false",required = false) boolean freeswitchCall) {
        try{
            CallTask callTask = callTaskBiz.getCallTaskById(taskId);
            String packageId = callTask.getPackageId();
            SpeakingPackage speakingPackage = speakingPackageBiz.selectById(packageId);
            String packageName = speakingPackage!=null?speakingPackage.getPackageName():"";
            CallVo callVo = getNextPhone(callTask.getId(),packageName,targetCallPhone,mainCallPhone,1);
            if(callVo!=null){
                String commitTo = CallTaskUtils.getCommitTo(aiCall?CallType.AI:CallType.MANUAL);
                callVo.setCommitTo(commitTo);
                callVo.setPackageName(packageName);
                model.addAttribute("commitTo",commitTo);//当前线路
                model.addAttribute("callVo",callVo);
                model.addAttribute("taskId",taskId);
                model.addAttribute("callTask",callTask);
                model.addAttribute("customerFollowCategorys",CustomerFollowCategory.values());
                model.addAttribute("customerNeedLevels", CustomerNeedLevel.values());
                model.addAttribute("cloudcallUrl", callUrl);
                model.addAttribute("connectWsUrl", wsUrl);
                model.addAttribute("callTime", Utils.date2DateTimeString(new Date()));
                model.addAttribute("targetCallPhone", callVo.getTargetCallPhone());
                model.addAttribute("mainCallPhone", callVo.getMainCallPhone());
                model.addAttribute("customerName", callVo.getCustomerName());
                model.addAttribute("aiCall", aiCall);
                if(callVo.getCommitTo()!=null && CommitTo.FREESWITCH.getValue().equals(callVo.getCommitTo())){
                    freeswitchCall = true;
                }
                model.addAttribute("freeswitchCall",freeswitchCall);
                model.addAttribute("freeswitchCallService",freeswitchCallService);
                boolean actionCodeBreak = true;
                String voiceCode = "test";
                String voiceText = "";
                List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(callTask.getPackageId(),SpeakingFlowType.MAIN);
                if(speakingFlows!=null && !speakingFlows.isEmpty()){
                    SpeakingFlow speakingFlow = Utils.getFirst(speakingFlows);
                    //根据任务包 对应的 话术包id
                    Map params = new HashMap();
                    params.put("packageId",callTask.getPackageId());
                    params.put("flowId",speakingFlow.getId());
                    params.put("firstStepByFlow","true");
                    params.put("page",1);
                    params.put("pageSize",1);
                    List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepList(params);
                    if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
                        SpeakingFlowStep speakingFlowStep = Utils.getFirst(speakingFlowStepList);
                        actionCodeBreak = speakingFlowStep.isActionCodeBreak();
                        voiceCode = speakingFlowStep.getRecordCodeNum()==null || "null".equalsIgnoreCase(speakingFlowStep.getRecordCodeNum())?"":speakingFlowStep.getRecordCodeNum();
                        voiceText = speakingFlowStep.getContent();
                    }
                }
                model.addAttribute("actionCodeBreak", actionCodeBreak);
                model.addAttribute("voiceCode", voiceCode);
                model.addAttribute("voiceText", voiceText);
            }
        }catch (IllegalArgumentException ie){
            model.addAttribute("errorMsg",ie.getMessage());
        }
        return "page/linkageCall/callDetail";
    }




    /**
     *
     * @param model
     * @param params
     * @return
     */
    @RequestMapping("/callDetailByCrm")
    public String callDetail(Model model,Map<String,Object> params) {
        CallVo callVo = getCallVoByCrm(params);
        if(callVo!=null){
            model.addAttribute("callVo",callVo);
            model.addAttribute("packageId",params.get("packageId"));
            model.addAttribute("customerFollowCategorys",CustomerFollowCategory.values());
            model.addAttribute("customerNeedLevels", CustomerNeedLevel.values());
            model.addAttribute("cloudcallUrl", callUrl);
            model.addAttribute("connectWsUrl", wsUrl);
            model.addAttribute("callTime", Utils.date2DateTimeString(new Date()));
            model.addAttribute("targetCallPhone", callVo.getTargetCallPhone());
            model.addAttribute("mainCallPhone", callVo.getMainCallPhone());
            model.addAttribute("customerName", callVo.getCustomerName());
            model.addAttribute("aiCall", params.get("aiCall"));
            model.addAttribute("freeswitchCall",params.get("freeswitchCall"));
            boolean actionCodeBreak = true;
            String voiceCode = "test";
            String voiceText = "";
            List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(params.get("packageId").toString(),SpeakingFlowType.MAIN);
            if(speakingFlows!=null && !speakingFlows.isEmpty()){
                SpeakingFlow speakingFlow = Utils.getFirst(speakingFlows);
                //根据任务包 对应的 话术包id
                Map condition = new HashMap();
                condition.put("packageId",params.get("packageId").toString());
                condition.put("flowId",speakingFlow.getId());
                condition.put("firstStepByFlow","true");
                condition.put("page",1);
                condition.put("pageSize",1);
                List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepList(condition);
                if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
                    SpeakingFlowStep speakingFlowStep = Utils.getFirst(speakingFlowStepList);
                    actionCodeBreak = speakingFlowStep.isActionCodeBreak();
                    voiceCode = speakingFlowStep.getRecordCodeNum()==null || "null".equalsIgnoreCase(speakingFlowStep.getRecordCodeNum())?"":speakingFlowStep.getRecordCodeNum();
                    voiceText = speakingFlowStep.getContent();
                }
            }
            model.addAttribute("actionCodeBreak", actionCodeBreak);
            model.addAttribute("voiceCode", voiceCode);
            model.addAttribute("voiceText", voiceText);
        }
        return "page/linkageCall/callDetail";
    }


    @RequestMapping("/setCallPhone")
    public String setCallPhone(Model model,String mainCallPhone,String targetCallPhone) {
        model.addAttribute("mainCallPhone",mainCallPhone);
        model.addAttribute("targetCallPhone",targetCallPhone);
        return "page/linkageCall/setCallPhone";
    }

    @RequestMapping("/viewCallDetail")
    public String viewCallDetail(Model model,String sessionId,String commitTo) {
        model.addAttribute("customerFollowCategorys",CustomerFollowCategory.values());
        model.addAttribute("sessionId",sessionId);
        model.addAttribute("customerNeedLevels", CustomerNeedLevel.values());
        model.addAttribute("cloudcallUrl", callUrl);
        model.addAttribute("callTime", Utils.date2DateTimeString(new Date()));
        model.addAttribute("commitTo", commitTo);
        Map paramMap = new HashMap<String,String>();
        paramMap.put("sessionId",sessionId);
        paramMap.put("sort","acs");//按创建时间升序 返回
//        todo
        Map<String,Object>  result = queryCallHistoryList(paramMap);
        Map<String,Object>  txtResult = queryCallHistoryTextList(paramMap);
        if(txtResult!=null && !txtResult.isEmpty()){
            List<Map> mapList = (List<Map>)txtResult.get("data");
            model.addAttribute("mapList",mapList);
        }
        Map callMap  = null;
        if("0".equals(result.get("code").toString()) && Integer.parseInt(result.get("count").toString())>0){
            List<Map> callMapList = (List<Map>)result.get("data");
            callMap = Utils.getFirst(callMapList);
        }
        model.addAttribute("callMap", callMap);
        String connectTime = "0秒";
        if(callMap!=null && !callMap.isEmpty()){
            String callStatus = callMap.get("failedReason")!=null?callMap.get("failedReason").toString():"";
            if(callMap.containsKey("recordTimeLength") && Utils.isNumber(callMap.get("recordTimeLength").toString()) && Integer.parseInt(callMap.get("recordTimeLength").toString())>0){
                callStatus = "已接通";
                connectTime = CallTaskUtils.getForMatTime(Long.parseLong(callMap.get("recordTimeLength").toString()) );
            }else{
                if(Utils.isNullString(callStatus) || "null".equals(callStatus)){
                    callStatus = "未接通";
                }
            }
            model.addAttribute("callStatus", callStatus);
            String firstSpeaking = "";//开场白
            if(callMap.containsKey("callTaskId")){
                String callTaskId = (String)callMap.get("callTaskId");
                CallTask callTask = callTaskBiz.selectById(callTaskId);
                if(callTask!=null){
                    List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(callTask.getPackageId(),SpeakingFlowType.MAIN);
                    if(speakingFlows!=null && !speakingFlows.isEmpty()){
                        SpeakingFlow speakingFlow = Utils.getFirst(speakingFlows);
                        //根据任务包 对应的 话术包id
                        Map params = new HashMap();
                        params.put("packageId",callTask.getPackageId());
                        params.put("flowId",speakingFlow.getId());
                        params.put("firstStepByFlow","true");
                        params.put("page",1);
                        params.put("pageSize",1);
                        List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepList(params);
                        if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
                            SpeakingFlowStep speakingFlowStep = Utils.getFirst(speakingFlowStepList);
                            firstSpeaking = speakingFlowStep.getContent();
                        }
                    }
                }
            }
            model.addAttribute("firstSpeaking", firstSpeaking);
        }

        model.addAttribute("connectTime", connectTime);

        return "page/linkageCall/viewCallDetail";
    }

    @ResponseBody
    @RequestMapping("/getNextPhone")
    public CallVo getNextPhone(String taskId,String packageName,String targetCallPhone,String mainCallPhone,int taskNum){
        taskNum++;
        CallTaskPhone callTaskPhone = callTaskPhoneBiz.getCanCallTaskPhone(taskId);

        CallVo callVo = null;
        if(callTaskPhone!=null){
            callVo = getCallVo(callTaskPhone);
            callVo.setPackageName(packageName);
            if(!Utils.isNullString(targetCallPhone)){
                callVo.setTargetCallPhone(targetCallPhone);
            }
            if(!Utils.isNullString(mainCallPhone) && Utils.validatorPhone(mainCallPhone)){
                callVo.setMainCallPhone(mainCallPhone);
            }
        }
        if(callVo!=null){
            //校验非数字 或 长度大于13 或 主叫号码=被叫号码 情况下
            if(!Utils.validatorPhone(callVo.getTargetCallPhone())
                    || !Utils.validatorPhone(callVo.getMainCallPhone())
                    || callVo.getTargetCallPhone().length()>13
                    || callVo.getMainCallPhone().length()>13
                    || callVo.getTargetCallPhone().equals(callVo.getMainCallPhone())
                    ){
                return getNextPhone(taskId,packageName,targetCallPhone,mainCallPhone,taskNum);
            }else{
                //如果是固话情况下，要去掉-，外呼的时候格式是不带-
                callVo.setTargetCallPhone(callVo.getTargetCallPhone().replaceAll("-",""));;
                callVo.setMainCallPhone(callVo.getMainCallPhone().replaceAll("-",""));;
            }
        }
        if(taskNum>0){
            CallTask callTask = callTaskBiz.getCallTaskById(taskId);
            callTask.setTakePhoneNum(callTask.getTakePhoneNum() + taskNum);
            callTaskBiz.update(callTask);
        }
        return callVo;
    }

    /**
     * 封装call客 参数
     * */
    public CallVo getCallVo(CallTaskPhone callTaskPhone){
        CallVo callVo = new CallVo();
        if(!Utils.isNullString(callTaskPhone.getCustomerName())){
            callVo.setCustomerName(callTaskPhone.getCustomerName());
        }else{
            callVo.setCustomerName("暂无客户姓名");
        }
        callVo.setMainCallPhone(callTaskPhone.getPhone());
        callVo.setWhereFrom(WhereFrom.AI_LINK_CALL.getValue());
        callVo.setPageFrom(PageFrom.PC_AI_CALL.getValue());
        callVo.setCityId(1);
        callVo.setCommitTo(CommitTo.INT_ALIYUN.getValue());
        callVo.setCreateUserId(UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0l);
        callVo.setProjectName("");
        callVo.setMainCallType("0");
        callVo.setSessionId(UUIDs.base64UUID()+"_"+IdGenerator.generate("callTaskPhone").toString());
        callVo.setToken((UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0l)+"_"+System.currentTimeMillis());
        callVo.setCallTaskId(callTaskPhone.getCallTaskId());
        callVo.setDataId(callTaskPhone.getDataId());
        callVo.setObjectId(callTaskPhone.getCallTaskId());
        return callVo;
    }


    /**
     * 封装call客 参数
     * long createUserId,
     * String customerName,
     * String mainPhone
     * String targetPhone
     * long cityId
     * */
    public CallVo getCallVoByCrm(Map<String,Object> param){
        CallVo callVo = new CallVo();
        callVo.setWhereFrom(WhereFrom.NEW_CUSTOMER.getValue());
        callVo.setPageFrom(PageFrom.PC_CUSTOMER.getValue());
        callVo.setCommitTo(CommitTo.INT_ALIYUN.getValue());
        callVo.setMainCallType("0");
        callVo.setSessionId(UUIDs.base64UUID());
        callVo.setCustomerName("暂无客户姓名");
        callVo.setCallTaskId("0");
        callVo.setDataId("0");
        param.entrySet().forEach(it->{
            switch (it.getKey()){
                case "customerName":
                    callVo.setCustomerName(param.get("customerName").toString());
                    break;
                case "mainPhone":
                    callVo.setMainCallPhone(param.get("mainPhone").toString());
                    break;
                case "targetPhone":
                    callVo.setTargetCallPhone(param.get("targetPhone").toString());
                    break;
                case "cityId":
                    callVo.setCityId((Long)param.get("cityId"));
                    break;
                case "createUserId":
                    callVo.setCreateUserId((Long)param.get("createUserId"));
                    callVo.setToken(param.get("createUserId").toString()+"_"+System.currentTimeMillis());
                    break;
            }
        });
        return callVo;
    }


    @ResponseBody
    @RequestMapping("/getSessionId")
    public String getSessionId(){
        String sessionId =  UUIDs.base64UUID()+"_"+IdGenerator.generate("callTaskPhone").toString();
        return  sessionId;
    }


    @ResponseBody
    @RequestMapping("/uploadPhoneExcel")
    public WebResult uploadPhoneExcel(@RequestParam MultipartFile file) {
        WebResult webResult = new WebResult();
        try {
            Workbook workbook = ExcelUtils.getExcelWorkbook(file.getInputStream());
            List<Sheet> sheetList = ExcelUtils.getSheetListByWorkbook(workbook);
            List<Map> phoneList = new ArrayList<Map>();
            for (Sheet sheet : sheetList) {
                List<Row> rowList = ExcelUtils.getRowListBySheet(sheet);
                if (rowList != null && !rowList.isEmpty()) {
                    rowList.remove(0);////去除第一行（文字标题行）
                    for (Row row : rowList) {
                        Cell nameCell = row.getCell(0);
                        Cell phoneCell = row.getCell(1);
                        nameCell.setCellType(1);
                        phoneCell.setCellType(1);
                        if(Utils.validatorPhone(phoneCell.getStringCellValue())){
                            Map phoneMap = new HashMap();
                            phoneMap.put("customerName", nameCell.getStringCellValue());
                            phoneMap.put("customerPhone", phoneCell.getStringCellValue());
                            phoneList.add(phoneMap);
                        }
                    }
                }
            }
            webResult.setTotal(phoneList.size());
            webResult.setMsg(GlobalStatic.SUCCESS);
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setRecords(phoneList);
        } catch (IOException e) {
            webResult.setMsg("读取文件异常");
            webResult.setCode(GlobalStatic.CODE_N2);
            webResult.setTotal(0);
            webResult.setRecords(null);
        } catch (Exception e) {
            webResult.setMsg(GlobalStatic.EXCEPTION_CHAR);
            webResult.setCode(GlobalStatic.CODE_N);
            webResult.setTotal(0);
            webResult.setRecords(null);
        }
        return webResult;
    }

    @ResponseBody
    @PostMapping("/saveLinkageCallTask")
    public WebResult saveLinkageCallTask(@RequestParam Map<String, String> params, HttpSession httpSession) {
        WebResult webResult = null;
        try {
            if (params.containsKey("selTaskSourceStr")) {
                List<Map> selTaskSourceMapList = JSON.parseArray(params.get("selTaskSourceStr"), Map.class);
                List<CallTaskPhone> callTaskPhoneList = new ArrayList<CallTaskPhone>();
                for (Map map : selTaskSourceMapList) {
                    if (CallTaskPhoneSource.UPLOAD_EXCEL.getValue().equals(map.get("type"))) {
                        String paramStr = map.get("param").toString();
                        if (StringUtil.isNotNull(paramStr)) {
                            List<Map> paramList = JSON.parseArray(paramStr, Map.class);
                            for (Map paramMap : paramList) {
                                CallTaskPhone callTaskPhone = new CallTaskPhone();
                                callTaskPhone.setCallTaskPhoneSource(CallTaskPhoneSource.UPLOAD_EXCEL);
                                callTaskPhone.setCustomerName(paramMap.get("customerName").toString());
                                callTaskPhone.setPhone(paramMap.get("customerPhone").toString());
                                callTaskPhoneList.add(callTaskPhone);
                            }
                        }
                    }
                }
                CallTask callTask = new CallTask();
                callTask.setCreateUserId(UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0l);
                callTask.setTaskName(params.get("taskName"));
                callTask.setPackageId(params.get("packageId"));
                callTask.setCallNum(Integer.parseInt(params.get("callNum")));
                webResult = callTaskBiz.addCallTask(callTask, callTaskPhoneList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            webResult = new WebResult(GlobalStatic.CODE_N, GlobalStatic.EXCEPTION_CHAR, 0, null, null);
        }
        return webResult;
    }

    @ResponseBody
    @RequestMapping("/queryCallTasks")
    public WebResult queryCallTasks(@RequestParam Map<String, String> params) {
        WebResult webResult = null;
        try {
            if (params != null && !params.isEmpty()) {
                if(params.containsKey("doSearch") && "false".equals(params.get("doSearch"))){
                    return WebResultUtils.getSuccessCharWebResult("",0,null);
                }
                //如果可以查全部时，移除限定的userId 进行查询
                if(params.containsKey("canSearchAll") && "true".equals(params.get("canSearchAll"))){
                    params.remove("createUserId");
                }

                List<Map<String, Object>> callTaskList = new ArrayList<>();
                /*if(params.containsKey("createTimeStart")){
                    params.put("createTimeStart",Utils.date2DateTimeString(Utils.string2Date(params.get("createTimeStart"),Utils.DATE_FORMAT_DATETIME)));
                }*/
                Page<CallTask> callTaskPage = callTaskBiz.queryCallTaskPage(params);
                if (StringTools.isNotempty(callTaskPage.getContent())) {
                    StringBuilder callTaskIds = new StringBuilder();
                    Set<String> userIds = new HashSet<>();
                    callTaskPage.getContent().forEach(it->{
                        userIds.add(it.getCreateUserId()+"");
                    });
                    Map<Integer,String> userMap = UserUtils.getUserNameMap(new ArrayList<>(userIds));
                    for (CallTask callTask : callTaskPage.getContent()) {
                        callTaskIds.append(callTask.getId()+",");
                        SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(callTask.getPackageId());
                        Integer takeNum = callTaskBiz.getTakePhoneNum(callTask.getId());
                        Map<String, Object> callTaskMap = new HashMap<>();
                        callTaskMap.put("callNum", callTask.getCallNum());//任务量
                        callTaskMap.put("takePhoneNum", takeNum);//已提取号码数量
                        callTaskMap.put("packageName", speakingPackage!=null?speakingPackage.getPackageName():"");//已提取号码数量
                       /* Map paramMap = new HashMap<String,String>();
                        paramMap.put("callTaskId",callTask.getId());
                        paramMap.put("sort","acs");//按创建时间升序 返回 /// 远程方法只能 传参一次，那且不是多次调用？？？不是有问题？
                        Map<String,Object>  result = queryCallHistoryList(paramMap);
                        if(result!=null && !result.isEmpty() && result.get("data")!=null){
                            List<Map> list  = (List<Map>)result.get("data");
                            Set<String> sessionIds = new HashSet<String>();
                            list.forEach(c->{
                                sessionIds.add(c.get("sessionId").toString());
                            });
                            if(sessionIds!=null && !sessionIds.isEmpty()){
                                callTaskMap.put("calledNum", sessionIds.size());//已call量
                            }
                        }*/
                        callTaskMap.put("taskName", callTask.getTaskName());
                        callTaskMap.put("projectName", callTask.getTaskName());
                        callTaskMap.put("createTime", DateUtils.toString(callTask.getCreateTime(), DateUtils.DATE_FORMAT_DATEONLY));
                        callTaskMap.put("status", callTask.getStatus());//任务状态
                        callTaskMap.put("createUserName", userMap.get(callTask.getCreateUserId())!=null?userMap.get(callTask.getCreateUserId()):"系统管理员");//创建人
                        callTaskMap.put("id", callTask.getId());//已call量
                        callTaskList.add(callTaskMap);

                       /* if(callTask.getStatus() == CallTaskStatus.FINISHED){
                            redisTemplate.opsForValue().increment(RedisKey.getTaskPhoneNumRedisKey(callTask.getId()),callTask.getCallNum());
                        }else{
                            Map resultMap = esOptRmiService.queryCallTaskDetailId(callTask.getId());
                            //判断成功与否,是否查询出数据
                            if (resultMap.containsKey("data") && resultMap.get("data") != null && !"null".equals(resultMap.get("data")) && !Utils.isNullString(resultMap.get("data").toString())) {
                                //将json转化为javaBean
                                String jsonString = (String) resultMap.get("data");
                                CallTaskDetail callTaskDetail = JSON.parseObject(jsonString, CallTaskDetail.class);
                                redisTemplate.opsForValue().increment(RedisKey.getTaskPhoneNumRedisKey(callTask.getId()),callTaskDetail.getProgress());
                            }
                        }*/
                    }

                    Map paramMap1 = new HashMap<String,String>();
                    paramMap1.put("callTaskIds",callTaskIds.toString());
                }
                webResult = new WebResult(GlobalStatic.CODE_1, GlobalStatic.SUCCESS_CHAR, callTaskPage.getTotalElements(), callTaskList, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            webResult = new WebResult(GlobalStatic.CODE_N, GlobalStatic.EXCEPTION_CHAR, 0, null, null);
        } finally {
            if (webResult == null) {
                webResult = new WebResult(GlobalStatic.CODE_N2, "传入参数异常", 0, null, null);
            }
        }
        return webResult;
    }

    /* //查看详情
     @RequestMapping("/viewCallTaskDetail")
     public String viewCallTaskDetail(@RequestParam String callTaskId, Model model) {
         Map map = new HashMap();
         map.put("id", callTaskId);

         try {
             List<CallTask> callTasks = callTaskBiz.getCallTaskList(map);
             CallTask callTask = Utils.getFirst(callTasks);
             Map<String, Object> callTaskMap = new HashMap<>();
             callTaskMap.put("taskName", callTask.getTaskName());
             callTaskMap.put("projectName", callTask.getTaskName());
             callTaskMap.put("createTime", DateUtils.toString(callTask.getCreateTime(), DateUtils.DATE_FORMAT_DATEONLY));
             callTaskMap.put("status", callTask.getStatus());//任务状态
             callTaskMap.put("createUserName", "张三");//创建人
             callTaskMap.put("callNum", 100);//任务量
             callTaskMap.put("calledNum", 5);//已call量
             callTaskMap.put("packageName", "广佛智城");//已call量
             callTaskMap.put("id", callTask.getId());//已call量
             model.addAttribute("callTaskMap", callTaskMap);
         } catch (Exception e) {
             e.printStackTrace();
         }
         return "page/linkageCall/queryLinkageCallTaskDetail";
     }*/
    //查看详情
    @RequestMapping("/viewCallTaskDetail")
    public String viewCallTaskDetail(@RequestParam String callTaskId, Model model) {
        try {
            //调用biz查询callTask
            CallTask callTask = callTaskBiz.selectById(callTaskId);
            CallTaskDetail callTaskDetail = null;

            Map<Integer,String> userMap = UserUtils.getUserNameMap(callTask.getCreateUserId());
            if (callTask != null) {
                String packageName = "暂无";
                SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(callTask.getPackageId());
                if(speakingPackage!=null){
                    packageName = speakingPackage.getPackageName();
                }
                //封装前台所需数据(callTask基本信息)
                Map<String, Object> callTaskMap = new HashMap<>();
                //createUserName先写死
                callTaskMap.put("createUserName", userMap.get(callTask.getCreateUserId())!=null?userMap.get(callTask.getCreateUserId()):"系统管理员");//创建人
                callTaskMap.put("packageName", packageName);//
                callTaskMap.put("taskName", callTask.getTaskName());
                callTaskMap.put("projectName", callTask.getTaskName());
                callTaskMap.put("id", callTask.getId());//callTask的Id
                callTaskMap.put("status", callTask.getStatus());//任务状态
                callTaskMap.put("createTime", DateUtils.toString(callTask.getCreateTime(), DateUtils.DATE_FORMAT_DATEONLY));
                callTaskMap.put("callNum", callTask.getCallNum());//任务量

                //调用dubbo接口查询callTaskDetail(详细信息)
                //Map<String, Object> resultMap = esOptRmiService.queryCallTaskDetailId(callTaskId);
                Map<String, Object> resultMap = callDataBiz.queryCallTaskDetailId(callTaskId);
                //判断成功与否,是否查询出数据
                if (resultMap.containsKey("data") && resultMap.get("data") != null && !"null".equals(resultMap.get("data")) && !Utils.isNullString(resultMap.get("data").toString())) {

                    //将json转化为javaBean
                    String jsonString = (String) resultMap.get("data");
                    callTaskDetail = JSON.parseObject(jsonString, CallTaskDetail.class);

                    //存入model
                    model.addAttribute("callTaskDetail", callTaskDetail);

                    //计算拨打进度
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(0);
                    String progress = "0";
                    int takePhoneNum = callTaskBiz.getTakePhoneNum(callTask.getId());
                    if(takePhoneNum>callTask.getCallNum() || callTask.getStatus() == CallTaskStatus.FINISHED){ // 当获取的号码次数大于当前资料包的号码数 或者 任务包的状态为 已call完情况下， 均返回100%
                        takePhoneNum =  callTask.getCallNum();
                    }
                    progress = numberFormat.format((float)takePhoneNum / (float) callTask.getCallNum() * 100);
                    callTaskMap.put("callProgress", progress );
                }


                //封装图表的显示对象
                List<PieVo> receptionStatusPieVos = new ArrayList<PieVo>();
                receptionStatusPieVos.add(new PieVo("connectedTimes","电话接通次数",callTaskDetail!=null?callTaskDetail.getConnectedTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("noOneReceiveTimes","无人接听",callTaskDetail!=null && callTaskDetail.getProgress()!=0 && callTaskDetail.getProgress()>callTaskDetail.getConnectedTimes()?(callTaskDetail.getProgress() - callTaskDetail.getConnectedTimes())+"":"0"));
               /* receptionStatusPieVos.add(new PieVo("rejectTimes","电话拒接次数",callTaskDetail!=null?callTaskDetail.getRejectTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("nullTimes","电话号码次数",callTaskDetail!=null?callTaskDetail.getNullTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("closeTimes","电话关机次数",callTaskDetail!=null?callTaskDetail.getCloseTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("stopUseTimes","电话停机次数",callTaskDetail!=null?callTaskDetail.getStopUseTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("onHookTimes","挂机次数",callTaskDetail!=null?callTaskDetail.getOnHookTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("inUseTimes","电话占线通次数",callTaskDetail!=null?callTaskDetail.getInUseTimes()+"":"0"));
                receptionStatusPieVos.add(new PieVo("noOneReceiveTimes","电话无人接听次数",callTaskDetail!=null?callTaskDetail.getNotConnectTimes()+"":"0"));*/

                List<PieVo> talkTimePieVos = new ArrayList<PieVo>();
                talkTimePieVos.add(new PieVo("callTimeLengthA","小于20s",callTaskDetail!=null?callTaskDetail.getCallTimeLengthA()+"":"0"));
                talkTimePieVos.add(new PieVo("callTimeLengthB","20s - 60s",callTaskDetail!=null?callTaskDetail.getCallTimeLengthB()+"":"0"));
                talkTimePieVos.add(new PieVo("callTimeLengthC","1min - 5min",callTaskDetail!=null?callTaskDetail.getCallTimeLengthC()+"":"0"));
                talkTimePieVos.add(new PieVo("callTimeLengthD","大于5min",callTaskDetail!=null?callTaskDetail.getCallTimeLengthD()+"":"0"));

                List<PieVo> callTurnsPieVos = new ArrayList<PieVo>();
                callTurnsPieVos.add(new PieVo("roundTimesA","0 - 3次",callTaskDetail!=null?callTaskDetail.getRoundTimesA()+"":"0"));
                callTurnsPieVos.add(new PieVo("roundTimesB","4 - 6次",callTaskDetail!=null?callTaskDetail.getRoundTimesB()+"":"0"));
                callTurnsPieVos.add(new PieVo("roundTimesC","7 - 10次",callTaskDetail!=null?callTaskDetail.getRoundTimesC()+"":"0"));
                callTurnsPieVos.add(new PieVo("roundTimesD","10次以上",callTaskDetail!=null?callTaskDetail.getRoundTimesD()+"":"0"));

                List<PieVo> customerLevelPieVos = new ArrayList<PieVo>();
                customerLevelPieVos.add(new PieVo("levelA","A级(较强)",callTaskDetail!=null?callTaskDetail.getLevelA()+"":"0"));
                customerLevelPieVos.add(new PieVo("levelB","B级(一般)",callTaskDetail!=null?callTaskDetail.getLevelB()+"":"0"));
                customerLevelPieVos.add(new PieVo("levelC","C级(很少)",callTaskDetail!=null?callTaskDetail.getLevelC()+"":"0"));
                customerLevelPieVos.add(new PieVo("levelD","D级(需筛选)",callTaskDetail!=null?callTaskDetail.getLevelD()+"":"0"));
                customerLevelPieVos.add(new PieVo("levelE","E级(需再次跟进)",callTaskDetail!=null?callTaskDetail.getLevelE()+"":"0"));
                customerLevelPieVos.add(new PieVo("levelF","F级(无需跟进)",callTaskDetail!=null?callTaskDetail.getLevelF()+"":"0"));


                List<Map<String,String>> _tags = new ArrayList<Map<String,String>>();
                /*
                List<String> tags = new ArrayList<String>();
                tags.add("女性");
                tags.add("有房一族");
                tags.add("刚需");
                tags.add("拥有房产5套");
                tags.add("客户意向物业类型: 住宅");
                tags.add("高收入家庭");
                tags.add("没有购买公积金");
                tags.add("投资买房");
                tags.add("活跃区域: 广州市-白云区");
                tags.add("需求房产所在区域: 广州市-白云区");
                tags.add("拥有房产在：荔湾区万兴苑,荔湾区芳泰花园,荔湾区花语水岸");
                tags.add("租价范围(元)：100(最低)，500(最高)");
                tags.add("其他需求: 其他");
                tags.add("近三个月看了：荔湾区芳泰花园");
                tags.forEach(r->{
                            Map map = new HashMap<String,String>();
                            map.put("someClass",GlobalStatic.analyseInfoHtmlClass.get((int) Math.round(Math.random() * 3)));
                            map.put("tabValues",r);
                            _tags.add(map);
                        }
                );*/

                if(callTaskDetail!=null && callTaskDetail.getWordCount()!=null  && !callTaskDetail.getWordCount().isEmpty()){
                    Map<String, Integer> map = callTaskDetail.getWordCount();
                    List<String> keywords = map.entrySet().stream().map(it->it.getKey()+"("+it.getValue()+")").collect(Collectors.toList());
                    keywords.forEach(kw->{
                        Map wordMap = new HashMap<String,String>();
                        wordMap.put("someClass",GlobalStatic.analyseInfoHtmlClass.get((int) Math.round(Math.random() * 3)));
                        wordMap.put("tabValues",kw);
                        _tags.add(wordMap);
                    });
                }
                model.addAttribute("receptionStatusPieVos", receptionStatusPieVos);
                model.addAttribute("talkTimePieVos", talkTimePieVos);
                model.addAttribute("callTurnsPieVos", callTurnsPieVos);
                model.addAttribute("customerLevelPieVos", customerLevelPieVos);
                model.addAttribute("tags", _tags);
                model.addAttribute("callTaskMap", callTaskMap);
            }
        } catch (Exception e) {

            e.printStackTrace();

            logger.error("查询callTask出错", e);
        }
        return "page/linkageCall/viewCallTaskDetailNew";
    }


    /**
     * 功能描述:获取通话记录,传到前台用于layui显示表格数据
     *
     * @param: [param]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @auther:
     * @date: 2018/9/3
     */
    @RequestMapping("queryCallHistoryList")
    @ResponseBody
    @PreProcessParam //根据参数返回对应的call客记录详情
    public Map<String, Object> queryCallHistoryList(@RequestParam Map<String, Object> param) {

        Map<String, Object> resultMap = null;

        try {
            //调用dubbo接口
            //Map<String, Object> map = esOptRmiService.queryCallHistoryList(param);
            Map<String, Object> map = callDataBiz.queryCallHistoryList(param);

            //状态码为10001,代表出异常
            if (((Integer) map.get("result")) == 10001) {

                resultMap = new HashMap<>();
                resultMap.put("code", "1");
                resultMap.put("msg", "服务器正忙,请稍后重试");

            } else {
                //状态码10000,成功
                //取出page的json字符串
                String pageJsonString = (String) map.get("data");

                //转化为对象
                Page<CallHistory> page = JSON.toJavaObject(JSON.parseObject(pageJsonString), Page.class);

                //调用工具类将page转为layui所需
                resultMap = LayUiParamUtils.getInstance().toLayuiTableMap(page);
            }
        } catch (Exception e) {
            logger.error("查询出现异常", e);
            e.printStackTrace();
            resultMap = new HashMap<>();
            resultMap.put("code", "1");
            resultMap.put("msg", "服务器正忙,请稍后重试");
        }
        return resultMap;
    }

    /**
     * 功能描述:获取通话记录,传到前台用于layui显示表格数据
     *
     * @param: [param]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @auther:
     * @date: 2018/9/3
     */
    @RequestMapping("queryCallHistoryTextList")
    @ResponseBody
    public Map<String, Object> queryCallHistoryTextList(@RequestParam Map<String, Object> param) {

        Map<String, Object> resultMap = null;

        try {

            //Map<String, Object> map = esOptRmiService.queryCallHistoryTextList(param);

            Map<String, Object> map =callDataBiz.queryCallHistoryTextList(param);

            //状态码为10001,代表出异常
            if (((Integer) map.get("result")) == 10001) {

                resultMap = new HashMap<>();
                resultMap.put("code", "1");
                resultMap.put("msg", "服务器正忙,请稍后重试");

            } else {
                //状态码10000,成功
                //取出page的json字符串
                String pageJsonString = (String) map.get("data");

                //转化为对象
                Page<CallHistory> page = JSON.toJavaObject(JSON.parseObject(pageJsonString), Page.class);

                //调用工具类将page转为layui所需
                resultMap = LayUiParamUtils.getInstance().toLayuiTableMap(page);

            }
        } catch (Exception e) {
            logger.error("查询出现异常", e);
            e.printStackTrace();
            resultMap = new HashMap<>();
            resultMap.put("code", "1");
            resultMap.put("msg", "服务器正忙,请稍后重试");
        }
        return resultMap;
    }


    @ResponseBody
    @RequestMapping("/getConnWsId")
    public String getConnWsId(){
        return CallTaskUtils.getWsConnParamsId();
    }


    /**
     * 保存反馈操作
     * */
    @ResponseBody
    @RequestMapping("/saveFeedBack")
    public WebResult saveFeedBack(@RequestParam String feedBack,@RequestParam String sessionId){
        Map map = new HashMap();
        map.put("customerFollowCategory",feedBack);
        map.put("sessionId",sessionId);
        System.out.println(sessionId);
        System.out.println(map.toString());
        //customerFollowCategory
        //String result = esOptRmiService.createOrUpdateCloudCallHistoryBySessionId(JSON.toJSONString(map));
        String result = callDataBiz.createOrUpdateCloudCallHistoryBySessionId(JSON.toJSONString(map));
        if(!Utils.isNullString(result) && "1".equals(result)){
            return WebResultUtils.getSuccessCharWebResult("",0,null);
        }
        return WebResultUtils.getFailCharWebResult(" 操作失败");
    }

    @ResponseBody
    @RequestMapping("/loadCallText")
    public WebResult loadCallText(String sessionId,int loadPage){
        WebResult webResult = WebResultUtils.getFailCharWebResult("");
        Map paramMap = new HashMap<String,String>();
        paramMap.put("sessionId",sessionId);
        paramMap.put("page",loadPage);
        paramMap.put("limit","10");
        paramMap.put("sort","acs");//按创建时间升序 返回
        Map<String,Object>  txtResult = queryCallHistoryTextList(paramMap);
        if(txtResult!=null && !txtResult.isEmpty()){
            List<Map> mapList = (List<Map>)txtResult.get("data");
            webResult = WebResultUtils.getSuccessCharWebResult("",Integer.parseInt(txtResult.get("count").toString()),(List<Map>)txtResult.get("data"));
        }
        return webResult;
    }

    @ResponseBody
    @RequestMapping("/delCallTask")
    public WebResult delCallTask(String callTaskId){
        WebResult webResult = WebResultUtils.getFailCharWebResult("");
        try {
            if(callTaskBiz.deleteById(callTaskId)){
                webResult = WebResultUtils.getSuccessCharWebResult("",0,null);
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }
        return  webResult;
    }


    /**
     * 提供CRM调用的接口
     * */
    @ResponseBody
    @RequestMapping("/saveLinkCallTask")
    public Map<String,Object> saveLinkCallTask(HttpServletRequest request,@RequestParam String callTaskVoJsonStr){
        if(Utils.isNullString(callTaskVoJsonStr)){
           callTaskVoJsonStr = request.getParameter("callTaskVoJsonStr");
        }
        ResultVo resultVo = WebResultUtils.getFailCharResulteVo("");
        Map<String,Object> result = null;
        try{
            CallTaskVo callTaskVo = JSON.parseObject(callTaskVoJsonStr,CallTaskVo.class);
            CallTask callTask = new CallTask();
            if(!Utils.isNullString(callTaskVo.getId())){
                callTask = callTaskBiz.getCallTaskById(callTaskVo.getId());
            }
            if(callTask == null){
                resultVo = WebResultUtils.getExceptionCharResulteVo("无法找到相应的call客任务包");
                return  JSON.parseObject(JSON.toJSONString(resultVo),Map.class);
            }
            if(Utils.isNullString(callTaskVo.getPackageId()) || Utils.isNullString(callTaskVo.getTaskName())
                    || (callTaskVo.getCallPhoneVoList()==null || callTaskVo.getCallPhoneVoList().isEmpty())){
                resultVo = WebResultUtils.getExceptionCharResulteVo("参数异常");
                return  JSON.parseObject(JSON.toJSONString(resultVo),Map.class);
            }
            callTask.setTaskName(callTaskVo.getTaskName());
            callTask.setStatus(CallTaskStatus.CALLING);
            callTask.setPackageId(callTaskVo.getPackageId());
            callTask.setProjectName(callTaskVo.getProjectName());
            callTask.setCreateUserId(UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0l);
            List<CallTaskPhone> callTaskPhoneList  = new ArrayList<CallTaskPhone>();
            for(CallPhoneVo callPhoneVo:callTaskVo.getCallPhoneVoList()){
                CallTaskPhone callTaskPhone = new CallTaskPhone();
                callTaskPhone.setPhone(callPhoneVo.getPhone());
                callTaskPhone.setCustomerName(callPhoneVo.getName());
                callTaskPhone.setCallTaskPhoneSource(CallTaskPhoneSource.EBOOK_CUSTOMER_INFO);
                callTaskPhone.setHadCalled(false);
                callTaskPhone.setDataId(callPhoneVo.getId());
                callTaskPhoneList.add(callTaskPhone);
            }
            WebResult webResult = null;
            if(Utils.isNullString(callTask.getId())){
                webResult = callTaskBiz.addCallTask(callTask,callTaskPhoneList);
            }else {
                webResult = callTaskBiz.saveCallTask(callTask,callTaskPhoneList);
            }
            if(webResult!= null && webResult.getCode() == GlobalStatic.CODE_1){
                resultVo = WebResultUtils.getSuccessCharResulteVo("",null);
            }

        }catch (Exception e){
            resultVo = WebResultUtils.getExceptionCharResulteVo("操作异常："+e.getMessage());
        }
        result = JSON.parseObject(JSON.toJSONString(resultVo),Map.class);
        return result;
    }

    @ResponseBody
    @RequestMapping("/getPageckageIdsByVo")
    public Map<String,Object> getPageckageIdsByVo(HttpServletRequest request,@RequestParam String searchPackageVoStr) {
        SearchPackageVo searchPackageVo = null;
        ResultVo resultVo = WebResultUtils.getFailCharResulteVo("");
        Map<String,Object> result = null;
        try{
            Map<String,String> params = new HashMap<String,String>();
            if(searchPackageVo!=null){
                if(!Utils.isNullString(searchPackageVo.getPackageName())){
                    params.put("packageName",searchPackageVo.getPackageName());
                }
                if(!Utils.isNullString(searchPackageVo.getId())){
                    params.put("id",searchPackageVo.getId());
                }
                if(searchPackageVo.getSpeakingPackageUseage()!=null){
                    params.put("speakingPackageUseage",searchPackageVo.getSpeakingPackageUseage().getValue());
                }
                if(searchPackageVo.getPackageType()!=null){
                    params.put("packageType",searchPackageVo.getPackageType().getValue());
                }
            }
            params.put("checkStatus", CheckStatus.YES.getValue());
            List<SpeakingPackage> speakingPackages = speakingPackageBiz.getSpeakingPackageList(params);
            List<Map> speakingPackageMap = new ArrayList<Map>();
            for(SpeakingPackage speakingPackage:speakingPackages){
                Map map = new HashMap();
                map.put("id",speakingPackage.getId());
                map.put("packageName",speakingPackage.getPackageName());
                map.put("type",speakingPackage.getPackageType());
                speakingPackageMap.add(map);
            }
            Map<String,Object> data = new HashMap<>();
            data.put("list", speakingPackageMap);
            data.put("total", speakingPackages.size());
            resultVo = WebResultUtils.getSuccessCharResulteVo("",data);
        }catch (Exception e){
            resultVo = WebResultUtils.getExceptionCharResulteVo("操作异常:"+e.getMessage());
        }
        result = JSON.parseObject(JSON.toJSONString(resultVo),Map.class);
        return result;
    }

    /**
     * 获取连接ws 的参数
     * */
    @ResponseBody
    @RequestMapping("/getConnWsParams")
    public Map<String,Object> getConnWsParams() {
        ResultVo resultVo = WebResultUtils.getFailCharResulteVo("");
        Map<String,Object> result = null;
        ConnectWsVo connectWsVo = CallTaskUtils.getConnectWsVo("33", PageFrom.PC_AI_CALL.getValue(),"3");
        Map<String,Object> data = new HashMap<>();
        data.put("list",  JSON.parseObject(JSON.toJSONString(connectWsVo),Map.class));
        resultVo = WebResultUtils.getSuccessCharResulteVo("",data);
        result = JSON.parseObject(JSON.toJSONString(resultVo),Map.class);
        return result;
    }

    @ResponseBody
    @RequestMapping("/getVoiceMapByPackageId")
    public Map<String,Object> getVoiceMapByPackageId(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        try{
            String packageId = request.getParameter("packageId");
            boolean actionCodeBreak = true;
            String voiceCode = "test";
            String voiceText = "";
            List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(packageId,SpeakingFlowType.MAIN);
            Map<String,Object> data = new HashMap<>();
            if(speakingFlows!=null && !speakingFlows.isEmpty()){
                SpeakingFlow speakingFlow = Utils.getFirst(speakingFlows);
                //根据任务包 对应的 话术包id
                Map condition = new HashMap();
                condition.put("packageId",packageId);
                condition.put("flowId",speakingFlow.getId());
                condition.put("firstStepByFlow","true");
                condition.put("page",1);
                condition.put("pageSize",1);
                List<SpeakingFlowStep> speakingFlowStepList = speakingFlowStepBiz.getSpeakingFlowStepList(condition);
                if(speakingFlowStepList!=null && !speakingFlowStepList.isEmpty()){
                    SpeakingFlowStep speakingFlowStep = Utils.getFirst(speakingFlowStepList);
                    actionCodeBreak = speakingFlowStep.isActionCodeBreak();
                    voiceCode = speakingFlowStep.getRecordCodeNum()==null || "null".equalsIgnoreCase(speakingFlowStep.getRecordCodeNum())?"":speakingFlowStep.getRecordCodeNum();
                    voiceText = speakingFlowStep.getContent();
                }
            }
            data.put("actionCodeBreak",actionCodeBreak);
            data.put("voiceCode",voiceCode);
            data.put("voiceText",voiceText);
            result.put("data",data);
            result.put("code",GlobalStatic.CODE_1);
            result.put("desc",GlobalStatic.SUCCESS_CHAR);
        }catch (Exception e){
            result.put("data",null);
            result.put("code",GlobalStatic.CODE_N);
            result.put("desc",GlobalStatic.SUCCESS_CHAR);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/checkFreeswitchUA")
    public WebResult checkFreeswitchUA(){
        WebResult result = new WebResult();
        try{
            Long uid = UserUtils.getCurrentUserId();
            String userName = "linkcall_"+uid;
            String requestUrl = checkUAUrl + "?userName="+userName+"&clientType=ihk";
            Map<String,Object> resultMap = restTemplate.getForObject(requestUrl,Map.class);
            if(resultMap!=null && resultMap.containsKey("code") && "1".equals(resultMap.get("code").toString())){
                result.setCode(GlobalStatic.SUCCESS);
                result.setMsg(userName);
            }else{
                result.setCode(GlobalStatic.FAIL);
                result.setMsg(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            result.setCode(GlobalStatic.FAIL);
            result.setMsg("检测账号操作异常"+e.getMessage());
        }
        return result;
    }

    /*@ResponseBody
    @RequestMapping("/test")
    public String test(HttpServletRequest httpRequest,@RequestParam String userName){
        System.out.println(userName);
        System.out.println(httpRequest.getParameter("userName"));
        Map<String,String> params = new HashMap<String,String>();
        params.put("checkStatus", CheckStatus.YES.getValue());
        List<SpeakingPackage> speakingPackages = speakingPackageBiz.getSpeakingPackageList(params);
        return httpRequest.getParameter("userName");
    }

    @ResponseBody
    @RequestMapping("/test")
    public String test(){
        MultiValueMap<String, Object> requestParam = new LinkedMultiValueMap<>();
        requestParam.set("userName","test");
        ZyUser zyUser = ThreadContextSessionHolder.getUser();
        if(zyUser!=null){
            requestParam.set("createUserId",zyUser.getId().toString());
        }
        // 通过 HttpHeaders 设置Form方式提交
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(requestParam, headers);
        String result = restTemplate.postForObject(linkcallWebUrl+"/linkageCall/test",httpEntity,String.class);
        return result;
    }*/
}
